package com.zhongke.common.base.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.fragment.app.Fragment
import com.zhongke.common.R
import com.zhongke.common.utils.gone

class ZKLazyLoadingFragment(
    private val child: Fragment,
    private val delayLoading: Boolean = false,
    private val showLoading: Boolean = true
) : VisibilityFragment() {

    private lateinit var loading: ProgressBar
    private val runnable = Runnable {
        childFragmentManager.beginTransaction()
            .add(R.id.fragmentContainer, child)
            .commit()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater.inflate(R.layout.commone_fragment_lazy_loading, container, false).also {
            loading = it.findViewById(R.id.loading)
            if (!showLoading) {
                loading.gone()
            }
        }
    }

    fun getChild() = child

    override fun onFirstVisible() {
        super.onFirstVisible()
        if (showLoading) {
            loading.postDelayed({
                loading.gone()
            }, 100)
        }

        if (delayLoading) {
            loading.postDelayed(runnable, 100)
        } else {
            runnable.run()
        }
    }

}